import React from 'react';
import {
  View,
  StyleSheet,
  ListView,
  Dimensions,
} from 'react-native';
import NavigationBar from 'react-native-navbar';
import FileTab from './FileTab';
import Repertory from '../core/Repertory';

export default class extends React.Component {
  constructor() {
    this.state = {
      items: [],
      itemsPerRow: 1,
    };
  }

  groupItems(items, itemsPerRow) {
    var itemsGroups = [];
    var group = [];
    items.forEach(function (item) {
      if (group.length === itemsPerRow) {
        itemsGroups.push(group);
        group = [item];
      } else {
        group.push(item);
      }
    });

    if (group.length > 0) {
      itemsGroups.push(group);
    }

    return itemsGroups;
  }

  renderGroup(group) {
    var that = this;
    var items = group.map(function (item) {
      return that.props.renderItem(item);
    });
    return (
      <View style={styles.group}>
          {items}
        </View>
    );
  }

  getReightButtonConfig() {
    const buttonConfig = {
      title: 'Forward',
      handler: () => this.props.navigator.push({
        component: CustomScreen,
      }),
    };
    return buttonConfig;
  }

  getLeftButtonConfig() {
    const buttonConfig = {
      title: 'Forward',
      handler: () => this.props.navigator.push({
        component: CustomScreen,
      }),
    };
    return buttonConfig;
  }

  getTitle() {
    // 根据宽度显示一个当前文件名或者多个文件名页签，要是屏幕较宽
    var {
      width
    } = Dimensions.get('window');
    if (width > 375) {
      // 显示多个页签
      const config = <FileTab />;
      return config;
    } else {
      const config = {
        title: ''
      };
      return config;
    }
  }

  render() {
    var groups = this.groupItems(this.state.items, this.state.itemsPerRow);
    var ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    });
    const rightButtonConfig = this.getRightButtonConfig();
    const leftButtonConfig = this.getLeftButtonConfig();
    return (<View style={{ flex: 1, backgroundColor: '#fff', }}>
      <NavigationBar
        title={this.getTitle()}
        leftButton={leftButtonConfig}
        rightButton={rightButtonConfig} />
        <ListView
              dataSource={ds.cloneWithRows(groups)}
              renderRow={this.renderGroup}
              style={this.props.style}
              onEndReached={this.props.onEndReached}
              scrollEnabled={this.props.scrollEnabled}
            />
    </View>);
  }
}

var styles = StyleSheet.create({
  group: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  }
});
